import { Component, OnInit,Input,Output,EventEmitter} from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import {config} from '../smartadmin.config';
declare var $: any;
@Component({
  	selector: 'table-select-car',
  	templateUrl: './mySelectCar.component.html',
  	styleUrls:['./mySelectCar.css'],
})
export class MySelectCarComponent implements OnInit{
	@Input() editPage: boolean;		// 条件为true 为添加编辑页面的选择样式
	@Input() noCompany: boolean;	// 条件为true 时不显示选择公司
	@Input() noCar: boolean;		// 条件为true 时不显示选择车辆
	@Input() preNext: boolean;		// 条件为true 时可以上下选择车辆
	@Output() private outerCar = new EventEmitter();
	companyName:string='';  		//选中的公司名称
	companyId:string='';			//选中的公司ID
	deviceId:string='';				//选中的车辆ID
	carNumber:string='';			//选中的车牌号码
	isAllowPre:boolean = false;
	isAllowNext:boolean = false;
	carList = [];
	constructor(private jsonApiService: JsonApiService) {}
	//将时间传递给父组件
	sendParent(){
		let selectedInfo={
			'companyName':this.companyName,
			'companyId':this.companyId,
			'deviceId':this.deviceId,
			'carNumber':this.carNumber,
		}
        this.outerCar.emit(selectedInfo);
    }
	ngOnInit(){
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				this.select2Car();//初始化select 2 车辆
			});
			System.import('assets/js/jstree/jstree.min.js').then(()=>{
				this.initCompanyList();
				this.companyCilckEvent();
				
			})
		});
	}
	companyCilckEvent(){
		var tree_box = document.getElementById('tree_box');
		var company = document.getElementById('company');
		if(!company) return;
		document.onclick=function(e:any){
			if(!(e.target === company||e.target.className === 'jstree-children'||e.target.className === 's_del_icon'||e.target.className === 'jstree-node  jstree-leaf'||e.target.className === 'jstree-icon jstree-ocl'||e.target.className ==='vision_tree'||e.target.className === 'jstree-node jstree-leaf jstree-closed')){ 
		        tree_box.className = tree_box.className.replace("tree_open","");
		   	}
		}
	}
	initCompanyList(){
		var that = this;
	 	$('#tree').jstree({
			"core": {
				'data': function(obj, callback) {       
					var jsonstr = "[]";       
					var jsonarray = eval('(' + jsonstr + ')');
					var url = 'company/companytree.html';
					$.ajax({        
						type: "GET",
				        url: config.BaseURL + url,
				        dataType: "json",
						xhrFields: {
							withCredentials: true
						},
				        success: function(result) {
							jsonarray = result;  
							callback.call(this, jsonarray);
						}         
					});   
			},

			"themes": {
				"responsive": true
			},
			"multiple": false,
			"animation": 200,
			"dblclick_toggle": true,
			"expand_selected_onload": true
		},
		"plugins": ["search"]
		}).bind("activate_node.jstree", function(e, obj) {
			var currentNode = obj.node; // 获取当前节点   
			that.companyName = currentNode.text;
			that.companyId = currentNode.id;
			that.queryCarListByCompanyId(currentNode.id);
			$('#company').val(currentNode.text).change();
			that.companySearch();
			that.sendParent()
		})
	}
	//拉取车辆数据
	select2Car(){
		var that = this;
        $("#carNumberSelect2").select2({
	    	language : "zh-CN",
	    	placeholder :"请选择",
	    	allowClear : true,
	    	minimumInputLength : 2,      //最少2个字符，select2才显示查询的内容
	         
	    	ajax: {
	    		url: config.BaseURL+"stats/carListByCarNumber.html",
	    		dataType: 'json',
	    		delay: 50,
	    		method: "POST",
	    		xhrFields: {
		           withCredentials: true
		      	},
	    		data: function (params) {
	    		    return {
	    		   	 "carNumber" :  params.term // search term
	    		    };
	    		},
	    		processResults: function(data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if(data.data.length<=10){
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if(arr.indexOf(car.carNumber)!=-1){
								sameCar.push(car.carNumber)
							}else{
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function(index, car) {
							if(sameCar.indexOf(car.carNumber)!=-1){
								options.push({
									id: car.deviceId,
									text: car.carNumber+"["+car.parentName+"]"
								})
							}else{
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					}else{
						$(data.data).each(function(index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
	    		cache: true
	         },
	         templateResult: this.formatRepo
	    }).on ("select2:select", function (e) {
        	  	var data = e.params.data;
				that.deviceId = data.id;
				  if(data.text.indexOf('[') > 0){
					that.carNumber = data.text.split('[')[0];
				} else {
					that.carNumber = data.text;
				}
        	  	that.sendParent()
       	});
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}
	//公司id拉取车辆
	queryCarListByCompanyId(companyId){
		this.deviceId='';
		this.carNumber='';	
		this.isAllowNext = false;
		this.isAllowPre = false;
		let reqdata = 'companyId='+companyId;
		this.jsonApiService.http("stats/carlist.html", reqdata).subscribe(data => {
			var carlist = data.data;
        	var selectdata = [];
        	for(var i = 0 ; i < carlist.length ; i++) {
        		var obj = {
        			id:carlist[i].deviceId,
        			text:carlist[i].carNumber,
        		}
        		selectdata[i] = obj;
        	}
        	if(this.preNext){
        		this.carList = selectdata;
        	}
        	var selectObj = $("#carNumberSelect2");
        	this.clearSelect2(selectObj);//清除Select中的数据
        	selectObj.select2({
        		language : "zh-CN",
            	data : selectdata,//为Select添加数据
                templateResult : this.formatRepo
           });
		})
	}
	
	
	//selcet2  车辆
	nextCar(type){
		this.isAllowNext = false;
		this.isAllowPre = false;
		if(this.carList.length >1&&this.deviceId){
			let len =  this.carList.length;
			for(let i = 0; i < len; i++){
				if(this.carList[i].text === this.carNumber&&this.carList[i].id === this.deviceId){
					if(type === 'pre'){
						if(i>0){
							this.carNumber = this.carList[i-1].text;
							this.deviceId = this.carList[i-1].id;
							$('#carNumberSelect2').val(this.deviceId).trigger('change');
							break;
						}else{
							this.isAllowPre = true;
							break;
						}
					}else if(type === 'next'){
						if(i<len-1){
							this.carNumber = this.carList[i+1].text;
							this.deviceId = this.carList[i+1].id;
							$('#carNumberSelect2').val(this.deviceId).trigger('change');
							break;
						}else{
							this.isAllowNext = true;
							break;
						}
					}
				}
			}
			this.sendParent();
		}
	}
	//擦除公司所选值
	delText(){
		this.companyName = '';
		this.companyId = '';
		this.deviceId = '';
		this.carNumber = '';
		this.carList = [];
		this.clearSelect2($("#carNumberSelect2"));//清除Select中的数据
		this.select2Car();
		$('#company').val("");
		this.companySearch();
		if($('#tree_box')[0].className.indexOf('tree_open')>0){
			$('#company').focus();
		}
		this.sendParent()
	}
	//擦除车牌号码所选值
	del_carNumber(){
		this.deviceId = '';
		this.carNumber = '';
		if(this.companyId){
			this.queryCarListByCompanyId(this.companyId)
		}else{
			//采用简单粗暴的方法清除;官方推荐的方法失效
			var str=$("<span class='select2-selection__placeholder'>请选择</span>");
			$('#carNumberSelect2').val("");
			$("#select2-carNumberSelect2-container").empty();
			$("#select2-carNumberSelect2-container").attr("title","");
			$("#select2-carNumberSelect2-container").prepend(str);
		}	
		this.sendParent()
	}
	//打开公司树
	companyClick(){
		$('#tree_box').toggleClass('tree_open');
	}
	//公司树模糊搜索
	companySearch(){
		var value = $('#company').val();
		$("#tree").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1){
			return;
		}
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#vision_tree'),
				scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#vision_tree').height() * 0.3});
			}
		})
	}

}